const Queue = require('bull');
const articleService = require('./article'); 
const directoryService = require('./directory'); 
const directoryArticleService = require('./directory-article'); 


const importArticleQueue = new Queue('importArticle');

importArticleQueue.process(async (job) => {
  const { file } = job.data;
  
  try {
    const { url, category } = file;
    const articleInfo = await articleService.importContent(url);
    const directoryInfo = await directoryService.findOne({ name: category[category.length - 1] });

    if (!directoryInfo) {
      throw new Error(`Directory not found for name: ${category}`);
    }

    await directoryArticleService.bind(articleInfo.id, directoryInfo.id);
    console.log(`Article imported and associated with directory for file: ${JSON.stringify(file)}`);
  } catch (error) {
    console.error(`Error processing job for file: ${JSON.stringify(file)}`, error);
  }
});

module.exports = importArticleQueue;